import socket
import struct
import json
import os
MY_FILE = os.path.join(os.path.dirname(__file__),'my_file')

def socket_server():
    server = socket.socket()

    server.bind(('127.0.0.1',8848))

    server.listen()

    conn, addr = server.accept()

    # 1. 接收固定长度的4个字节
    four_bytes = conn.recv(4)

    # 2. 利用struct反解
    head_len = struct.unpack('i',four_bytes)[0]

    # 3. 接收bytes类型的报头
    head_dic_json_bytes = conn.recv(head_len)

    # 4. 将bytes类型的报头转化成json
    head_dic_json = head_dic_json_bytes.decode('utf-8')

    # 5. 将json类型报头转化成字典形式的报头
    head_dic = json.loads(head_dic_json)

    # 有一个MD5校验

    # 6. 接收原始数据
    with open(os.path.join(MY_FILE,head_dic['new_file_name']),mode='wb') as f1:

        total_size = 0

        while total_size < head_dic['file_size']:
            every_data = conn.recv(1024)
            f1.write(every_data)
            total_size += len(every_data)

    conn.close()
    server.close()

socket_server()
